/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.helwen.restaurantbooking.ui;

import com.helwen.restaurantbooking.bo.IBookingBo;
import com.helwen.restaurantbooking.bo.ITableBo;
import com.helwen.restaurantbooking.datalayer.entities.TblBooking;
import com.helwen.restaurantbooking.datalayer.entities.TblTable;
import com.helwen.restaurantbooking.helper.BeanManagerHelper;
import com.toedter.calendar.JDateChooser;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;


import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Nghiata
 */
public class ReservationPanel extends JPanel {

    private static final IBookingBo BOOKING_BO = (IBookingBo) BeanManagerHelper.getBean("bookingBo");
    private static final ITableBo TABLE_BO = (ITableBo) BeanManagerHelper.getBean("tableBo");
    private JTextField txtName;
    private JTextField txtContact;
    private JDateChooser dcDate;
    private JComboBox cbxTime;
    private JComboBox cbxStaffName;
    private JComboBox cbxArea;
    private JComboBox cbxTableNumber;
    private JTextField txtNumberOfPack;
    private JTextField txtRemarks;
    private JButton btnSave;
    private JButton btnReset;
    private boolean isEditPanel = false;
    private JButton btnBook;
    private JButton btnRelease;
    public TblBooking tblBooking = new TblBooking();
    private JLabel errorLabel = new JLabel();
    private JButton btnClose;
    private Integer tableNumberSelected;
    private Area parentComponent;
    private MainUI mainUI;

    public Integer getTableNumberSelected() {
        return tableNumberSelected;
    }

    public void setTableNumberSelected(Integer tableNumberSelected) {
        this.tableNumberSelected = tableNumberSelected;
    }

    public ReservationPanel() {
        initLayout();
        initData();
    }

    public ReservationPanel(boolean isEditPanel) {
        this.isEditPanel = isEditPanel;
        initLayout();
        initData();

    }

    private void initLayout() {
        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.add(errorLabel);
        GridLayout gridLayout = new GridLayout(0, 2, 10, 10);

        txtName = new JTextField();
        txtContact = new JTextField();
        txtContact.addKeyListener(new KeyListener() {
            public void keyTyped(KeyEvent e) {
                validateKey(e);
            }

            public void keyPressed(KeyEvent e) {
                validateKey(e);
            }

            public void keyReleased(KeyEvent e) {
                validateKey(e);
            }

            private void validateKey(KeyEvent e) {
                char c = e.getKeyChar();
                if (c < 48 || c > 57) {
                    txtContact.setText("");
                }
            }
        });
        dcDate = new JDateChooser();
        dcDate.setDateFormatString("EEE , dd MMM yyyy");
        dcDate.setDate(new Date());
        dcDate.setMinSelectableDate(new Date());
        if (!isEditPanel) {
            dcDate.getDateEditor().addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    if ("date".equals(e.getPropertyName())) {
                        Date selectedDate = (Date) e.getNewValue();
                        if (selectedDate.after(new Date())) {
                            cbxTime.removeAllItems();
                            for (int i = 9; i < 22; i++) {
                                if (i < 12) {
                                    cbxTime.addItem(i + 1 + " am");
                                } else if (i >= 12 && i < 23) {
                                    cbxTime.addItem(i - 11 + " pm");
                                } else {
                                    cbxTime.addItem(0 + " am");
                                }

                            }
                            cbxTime.setEnabled(true);
                            btnSave.setEnabled(true);
                            btnReset.setEnabled(true);
                        }
                        if (selectedDate.getDate() == new Date().getDate()) {
                            cbxTime.removeAllItems();
                            int hours = new Date().getHours();
                            if (hours >= 22) {
                                cbxTime.setEnabled(false);
                                btnSave.setEnabled(false);
                                btnReset.setEnabled(false);
                            } else if (hours < 10) {
                                for (int i = 9; i < 22; i++) {
                                    if (i < 12) {
                                        cbxTime.addItem(i + 1 + " am");
                                    } else if (i >= 12 && i < 23) {
                                        cbxTime.addItem(i - 11 + " pm");
                                    } else {
                                        cbxTime.addItem(0 + " am");
                                    }

                                }
                            } else {
                                for (int i = hours; i < 22; i++) {
                                    if (i < 12) {
                                        cbxTime.addItem(i + 1 + " am");
                                    } else if (i >= 12 && i < 23) {
                                        cbxTime.addItem(i - 11 + " pm");
                                    } else {
                                        cbxTime.addItem(0 + " am");
                                    }

                                }
                            }
                        }
                    }
                }
            });
        }



        cbxTime = new JComboBox();
        cbxStaffName = new JComboBox(new String[]{"A", "B", "C"});
        cbxArea = new JComboBox();
        cbxTableNumber = new JComboBox();
        txtNumberOfPack = new JTextField();
        txtNumberOfPack.addKeyListener(new KeyListener() {
            public void keyTyped(KeyEvent e) {
                validateKey(e);
            }

            public void keyPressed(KeyEvent e) {
                validateKey(e);
            }

            public void keyReleased(KeyEvent e) {
                validateKey(e);
            }

            private void validateKey(KeyEvent e) {
                char c = e.getKeyChar();
                if (c < 48 || c > 57) {
                    txtNumberOfPack.setText("");
                }

            }
        });
        txtRemarks = new JTextField();
        if (isEditPanel) {
            btnSave = new JButton("Update");

        } else {
            btnSave = new JButton("Save");

        }
        btnSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (tblBooking.getId() == null && isEditPanel) {
                } else {
                    btnSaveClick(e);
                }
            }
        });


        JPanel form = new JPanel();
        form.setLayout(gridLayout);
        form.add(new JLabel("Name:"));
        form.add(txtName);

        form.add(new JLabel("Contact:"));
        form.add(txtContact);

        form.add(new JLabel("Date:"));
        form.add(dcDate);

        if (!isEditPanel) {
            form.add(new JLabel("Time:"));
            form.add(cbxTime);
        }


        form.add(new JLabel("Staff:"));
        form.add(cbxStaffName);
        if (!isEditPanel) {
            form.add(new JLabel("Area:"));
            form.add(cbxArea);
        }

        form.add(new JLabel("Table Number:"));
        form.add(cbxTableNumber);

        form.add(new JLabel("Number of Pack:"));
        form.add(txtNumberOfPack);

        if (!isEditPanel) {
            form.add(new JLabel("Remarks:"));
            form.add(txtRemarks);
        }
        form.add(btnSave);
        if (isEditPanel) {
            btnBook = new JButton("Occupy");
            form.add(btnBook);
            btnBook.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    btnBookClick(e);
                }
            });

            btnRelease = new JButton("Release");
            form.add(btnRelease);

            btnRelease.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    btnReleaseClick(e);
                }
            });
            btnClose = new JButton("Close");
            btnClose.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                }
            });
            form.add(btnClose);
        } else {
            btnReset = new JButton("Reset");
            btnReset.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    resetData();
                }
            });
            form.add(btnReset);

        }


        this.add(form);
    }

    private void initData() {
        if (!isEditPanel) {
            cbxArea.addItem("All Room");
        }
        cbxArea.addItem("Non-Smoking Room");
        cbxArea.addItem("Smoking Room");
        for (int i = 0; i < 5; i++) {
            cbxTableNumber.addItem(i + 1);
        }
        //Time
        int hours = new Date().getHours();
        if (hours >= 22) {
            cbxTime.setEnabled(false);
            btnSave.setEnabled(false);
            if (btnReset != null) {
                btnReset.setEnabled(false);
            }
        } else if (hours < 10) {
            for (int i = 9; i < 22; i++) {
                if (i < 12) {
                    cbxTime.addItem(i + 1 + " am");
                } else if (i >= 12 && i < 23) {
                    cbxTime.addItem(i - 11 + " pm");
                } else {
                    cbxTime.addItem(0 + " am");
                }

            }
        } else {
            for (int i = hours; i < 22; i++) {
                if (i < 12) {
                    cbxTime.addItem(i + 1 + " am");
                } else if (i >= 12 && i < 23) {
                    cbxTime.addItem(i - 11 + " pm");
                } else {
                    cbxTime.addItem(0 + " am");
                }

            }
        }


    }

    private void btnSaveClick(ActionEvent event) {
        List<String> error = BOOKING_BO.validateInputform(tblBooking.getId(), txtName, txtContact, dcDate, cbxTime, cbxArea, cbxTableNumber, txtNumberOfPack);
        errorLabel.setText("");
        if (error.isEmpty()) {
            SimpleDateFormat sim = new SimpleDateFormat("EEE , dd MMM yyyy");
            String time = sim.format(dcDate.getDate());
            BOOKING_BO.saveOrUpdate(tblBooking.getId(), txtName, txtContact, dcDate, cbxTime, cbxStaffName, cbxArea, cbxTableNumber, txtNumberOfPack, txtRemarks, new Short("0"));
            Integer numberOfPack = new Integer(txtNumberOfPack.getText());
            if (numberOfPack <= 5) {
                JOptionPane.showMessageDialog(null, "Table number " + cbxTableNumber.getSelectedItem().toString() + ", " + cbxArea.getSelectedItem().toString() + ", " + cbxTime.getSelectedItem().toString() + " " + time, "Successful", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "[" + cbxArea.getSelectedItem().toString() + "]Reserve on: " + cbxTime.getSelectedItem().toString() + ", " + time, "Successful", JOptionPane.INFORMATION_MESSAGE);
            }
            if (!isEditPanel) {
                mainUI.doSchedule();
            } else {
                parentComponent.resetListTable();
            }
        } else {
            StringBuilder str = new StringBuilder();
            str.append("<html>");
            str.append("<FONT COLOR=RED><I>");
            str.append("<ul>");
            for (String string : error) {

                str.append("<li>");
                str.append(string);
                str.append("</li>");
            }
            str.append("</ul>");
            str.append("</FONT></I>");
            str.append("</html>");
            JOptionPane.showMessageDialog(null, str.toString(), "Invalid Input", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void btnBookClick(ActionEvent e) {
        if (tblBooking != null) {
            tblBooking.setStatus(new Short("1"));
            tblBooking.getTblTable().setStatus(new Short("2"));
            BOOKING_BO.saveOrUpdate(tblBooking);
            resetData();
            parentComponent.resetListTable();
        }
        if (tblBooking == null) {
            int number = getTableNumberSelected();
            String area = "Non-Smoking Room";
            if (number > 5) {
                area = "Smoking Room";
            }
            List<String> error = BOOKING_BO.validateBookForm(txtName, txtContact, cbxTableNumber, cbxArea, txtNumberOfPack);
            errorLabel.setText("");
            if (error.isEmpty()) {
                BOOKING_BO.inserBooking(txtName, txtContact, dcDate, new Short("0"), cbxStaffName, area, number, txtNumberOfPack);
                Integer numberOfPack = new Integer(txtNumberOfPack.getText());
                if (numberOfPack < 5) {
                    JOptionPane.showMessageDialog(null, "Table number " + number + ", " + area + ", " + dcDate.getDate(), "Successful", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "[" + area + "]Reserve on: " + dcDate.getDate(), "Successful", JOptionPane.INFORMATION_MESSAGE);
                }
                resetData();
                parentComponent.resetListTable();
            } else {
                StringBuilder str = new StringBuilder();
                str.append("<html>");
                str.append("<FONT COLOR=RED><I>");
                str.append("<ul>");
                for (String string : error) {

                    str.append("<li>");
                    str.append(string);
                    str.append("</li>");
                }
                str.append("</ul>");
                str.append("</FONT></I>");
                str.append("</html>");
                JOptionPane.showMessageDialog(null, str.toString(), "Invalid Input", JOptionPane.WARNING_MESSAGE);
            }
        }

    }

    private void btnReleaseClick(ActionEvent e) {
        if (tblBooking.getId() != null) {
            if (tblBooking.getStatus() == 0) {
                tblBooking.setStatus(new Short("3"));
            } else if (tblBooking.getStatus() == 1) {
                tblBooking.setStatus(new Short("2"));
            }
            tblBooking.getTblTable().setStatus(new Short("0"));
            BOOKING_BO.saveOrUpdate(tblBooking);
            resetData();
            parentComponent.resetListTable();
        }
    }

    public void refreshUI() {
        if (tblBooking == null) {
            resetData();
        }
        if (tableNumberSelected != null) {

            if (tableNumberSelected > 6) {
                cbxTableNumber.setSelectedItem(tableNumberSelected - 5);
            } else {
                cbxTableNumber.setSelectedItem(tableNumberSelected);
            }
            cbxTableNumber.setEnabled(false);

            TblTable tblTable = TABLE_BO.getTableByNumber(tableNumberSelected);
            if (tblTable.getStatus() == 0) {
                btnSave.setEnabled(false);
                btnRelease.setEnabled(false);
                txtNumberOfPack.setEditable(true);
                btnBook.setEnabled(true);
            } else if (tblTable.getStatus() == 1) {
                btnBook.setEnabled(true);
                btnSave.setEnabled(true);
                btnRelease.setEnabled(true);
                txtNumberOfPack.setEditable(false);
                dcDate.setEnabled(false);
            } else {
                btnSave.setEnabled(false);
                btnBook.setEnabled(false);
                btnRelease.setEnabled(true);
                txtNumberOfPack.setEditable(false);
            }
//            tblBooking=BOOKING_BO.ge
        }
        if (tblBooking != null) {
            if (isEditPanel && tblBooking.getStatus() == 1) {
                btnBook.setEnabled(false);
                btnSave.setEnabled(false);
            }

            txtName.setText(tblBooking.getCustomerName());
            txtContact.setText(tblBooking.getContact());
            dcDate.setDate(tblBooking.getReservationDate());
            Short time = tblBooking.getReservationTime();
            if (time > 0 && time < 13) {
                cbxTime.setSelectedItem(time + " am");
            } else if (time >= 13 && time < 24) {
                cbxTime.setSelectedItem(time - 12 + " pm");
            } else {
                cbxTime.setSelectedItem(10 + " am");
            }

            cbxStaffName.setSelectedItem(tblBooking.getStaffName());
            if (tblBooking.getTblTable().getArea().equals("non-smoking")) {
                cbxArea.setSelectedItem("Non-Smoking Room");
            } else {
                cbxArea.setSelectedItem("Smoking Room");
            }
            cbxTableNumber.setEnabled(false);
            txtNumberOfPack.setText(tblBooking.getNumberOfPack() + "");
            txtRemarks.setText(tblBooking.getRemarks());
        }

    }

    private void resetData() {
        txtName.setText("");
        txtContact.setText("");
        dcDate.setDateFormatString("EEE , dd MMM yyyy");
        dcDate.setDate(new Date());
        if (cbxTime.isEnabled()) {
            cbxTime.setSelectedIndex(0);
        }
        cbxStaffName.setSelectedIndex(0);
        cbxArea.setSelectedIndex(0);
        cbxTableNumber.setSelectedIndex(0);
        txtNumberOfPack.setText("");
        txtRemarks.setText("");
    }

    public Area getParentComponent() {
        return parentComponent;
    }

    public void setParentComponent(Area parentComponent) {
        this.parentComponent = parentComponent;
    }

    public MainUI getMainUI() {
        return mainUI;
    }

    public void setMainUI(MainUI mainUI) {
        this.mainUI = mainUI;
    }
}
